package com.dynabook.ems.disruptor.BorrowUpdate;

import cn.hutool.core.thread.ThreadFactoryBuilder;
import com.lmax.disruptor.dsl.Disruptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

@Configuration
@Slf4j
public class BorrowUpdateDisruptorConfig {

    @Resource
    private BorrowUpdateEventHandler borrowUpdateEventHandler;

    @Resource
    private BorrowCustomExceptionHandler borrowCustomExceptionHandler;

    @Bean("borrowUpdateDisruptor")
    public Disruptor<BorrowUpdateEvent> borrowUpdateDisruptor() {
        // 定义环形大小
        int bufferSize = 1024 * 64; // 适当调小，因为每个事件包含的数据量较大
        Disruptor<BorrowUpdateEvent> disruptor = new Disruptor<>(
                new BorrowUpdateEventFactory(),
                bufferSize,
                ThreadFactoryBuilder.create().setNamePrefix("borrowUpdate-").build()
        );
        disruptor.setDefaultExceptionHandler(borrowCustomExceptionHandler);
        // 使用多个消费者并行处理
        disruptor.handleEventsWithWorkerPool(
                borrowUpdateEventHandler,
                borrowUpdateEventHandler,
                borrowUpdateEventHandler,
                borrowUpdateEventHandler
        );
        disruptor.start();
        return disruptor;
    }
}